<template>
	<view class="content">
		<navBar>
			<template @click="backPage()" slot="left">
				<u-icon name="arrow-left" color="#fff"></u-icon>
			</template>
			<template class="centerText" slot="center">
				<view class="" style="color: #fff">物料借用</view>
			</template>
		</navBar>
		<view class="top_box">
			<view class="title">录入信息 快捷完成借用</view>
			<view class="procedure">
				<u-steps :current="computeCurrent">
					<u-steps-item title="录入信息"></u-steps-item>
					<u-steps-item title="扫描/选择物料"></u-steps-item>
					<u-steps-item title="提交"></u-steps-item>
				</u-steps>
			</view>
		</view>
		<!-- 信息录入 -->
		<view class="information_entry">
			<!-- <u-read-more  :showHeight="200" ref="uReadMore"  @load="load" > -->
			<u--form labelPosition="left" ref="uForm" labelWidth="80" :model="formData" :rules="rules">
				<u-form-item @click="show = true" required label="借用日期" borderBottom ref="item1">
					{{ $u.timeFormat(formData.apply_time, 'yyyy-mm月-dd日') }}
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>

				<u-form-item required label="借用人" borderBottom ref="item1">
					<u--input v-model="userNmae" disabled disabledColor="#ffffff" placeholder="请输入借用人"
						border="none"></u--input>
				</u-form-item>
				<!-- <u-form-item @click="sectionPickerShow = true" required label="部门名称" prop="formData.stash" borderBottom
					ref="item1">
					<u--input disabled disabledColor="#ffffff" placeholder="请选择部门" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item> -->
				<u-form-item @click="showProject" required label="项目名称" prop="project" borderBottom ref="item1">
					<u--input disabled v-model="formData.project" disabledColor="#ffffff" placeholder="请选择项目名称"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<template v-if="loadMoreFlag">
					<u-form-item label="上传凭证" borderBottom ref="item1">
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="8" deletable>
							<template>
								<view class="upload_box">+</view>
							</template>
						</u-upload>
					</u-form-item>
					<u-form-item label="备注信息" borderBottom>
						<u--textarea v-model="formData.remark" maxlength="50" count placeholder="请输入内容"></u--textarea>
					</u-form-item>
				</template>
				<loadMore :loadMoreFlag.sync='loadMoreFlag'></loadMore>
			</u--form>
			<!-- </u-read-more> -->
		</view>
		<view class="scan_code">
			<view class="left_box" @click="scanCode">
				<image src="../../static/images/saoma.png" mode=""></image>
				<view>扫描条码 快速识别物品</view>
			</view>
			<view class="right_box" @click="manualSelection()">
				<image src="../../static/images/shoudong.png" mode=""></image>
				<view>手动添加</view>
			</view>
		</view>
		<!-- 物料清单 -->
		<view class="cargo_list">
			<view
				style=" display: flex;justify-content: space-between; align-items: center; padding-bottom: 30rpx; border-bottom: 1rpx solid #dadbde">
				<text class="big_title">物料借用清单</text>
				<text class="tips">左滑移除</text>
			</view>
			<view @click="manualSelection()" class="empty_box" v-if="cartList.length == 0">
				<u-empty text="点击添加需要借用的物料"></u-empty>
			</view>
			<!-- 商品列表 -->
			<goodsItem @change='change()' v-else></goodsItem>
		</view>
		<!-- 提交 -->
		<view class="bottom_box">
			<view class="submit_btn">
				<u-button @click="submit()" color="#39cccc" shape="circle" type="primary" text="提交"></u-button>
			</view>
		</view>
		<!-- 年月日选择 -->
		<u-datetime-picker title="借用日期" ref="datetimePicker" :show="show" v-model="formData.apply_time" mode="date"
			:formatter="formatter" @cancel="show = false" @confirm="dateConfirm()"></u-datetime-picker>
		<!-- 手动选择弹出层 -->
		<manualSelectionPopup ref="selectPopup" :is_back='is_back' :show.sync="showManualSelectionPopup">
		</manualSelectionPopup>
		<!-- 部门选择器 -->
		<u-picker keyName="label" :show="sectionPickerShow" ref="uPicker" :columns="columns" @confirm="confirm"
			@change="changeHandler"></u-picker>
		<projectList :showProjectPopup.sync='showProjectPopup'></projectList>
	</view>
</template>

<script>
	import navBar from '@/components/navBar.vue';
	import manualSelectionPopup from '@/components/manualSelectionPopup.vue';
	import goodsItem from '@/components/goodsItem.vue';
	import loadMore from '@/components/loadMore.vue'
	import projectList from '@/components/projectList.vue'
	import {
		mapState,
		mapMutations,
		mapGetters
	} from 'vuex'
	import {
		getSectionListApi,
		receiveAndBorrowApi,
		getGoodsByScancodeApi
	} from '@/api/receiveAndBorrow.js'
	export default {
		data() {
			return {
				formData: {
					apply_time: Number(new Date()),
					project: '',
					remark: '',
					ware_id: this.$store.state.user.stashInfo.ware_id,
					shipment_type: 23, // 22 领取 23 借用
					dept_id: 0, //部门
					attachment: '', //附件信息
				},
				is_back: 1,
				userNmae: '',
				sectionPickerShow: false, //部门选择器
				topCurrent: 0,
				fileList1: [], //上传图片列表
				show: false,
				showManualSelectionPopup: false, //手动选择
				rules: {
					project: {
						required: true,
						message: '请填输入项目名称',
						trigger: ['blur'],
					},
				},
				columns: [

				],
				columnData: [

				],
				loadMoreFlag: false,
				showProjectPopup: false
				// goodsItemList: this.$store.state.cart.cart
			};
		},
		mounted() {
			// this.getSectionList()
			const that = this
			uni.getStorage({
				key: 'userInfo',
				success(res) {
					that.userNmae = res.data.username
				}
			})
		},
		computed: {
			computeCurrent() {
				return this.cartList.length > 0 ? 2 : 1
			},
			...mapGetters([
				'cartList'
			])
		},
		onUnload() {
			this.clearCart()
		},
		components: {
			navBar,
			manualSelectionPopup,
			goodsItem,
			loadMore,
			projectList
		},
		methods: {
			//滑动后删除更新列表
			change() {
				this.$refs.selectPopup.setList()
			},
			...mapMutations('cart', ['clearCart', 'addToCart']),
			backPage() {
				if (this.cartList.length == 0) return uni.navigateBack()
				const that = this
				uni.showModal({

					content: '数据还没有提交确定退出吗',
					success: function(res) {
						if (res.confirm) {
							that.clearCart()
							uni.navigateBack();
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			load() {
				this.$refs.uReadMore.init();
			},
			showDate() {
				this.show = true;
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`;
				}
				if (type === 'month') {
					return `${value}月`;
				}
				if (type === 'day') {
					return `${value}日`;
				}
				return value;
			},
			hideKeyboard(e) {
				uni.hideKeyboard();
			},
			scanCode() {
				const that = this
				uni.scanCode({
					scanType: ['barCode'],
					success: async (e) => {
						const goods_no = e.result
						const {
							data: {
								data
							}
						} = await getGoodsByScancodeApi({
							goods_no: e.result,
							ware_id: this.$store.state.user.stashInfo.ware_id, //仓库ID
						})
						if (data.is_back != 1) return uni.$u.toast('该物料不能借用')
						this.addToCart(data)
						// this.getGoodsById()
						// that.$refs.selectPopup.pageInfo.goods_no = e.result
						// await that.$refs.selectPopup.getGoodsById()
						// that.$refs.selectPopup.pageInfo.goods_no = ''
						// if (that.$refs.selectPopup.goodsList.length == 0) {
						// 	uni.$u.toast('暂无此物料')
						// 	setTimeout(async () => {
						// 		await that.$refs.selectPopup.getGoodsById()
						// 	}, 500)
						// 	return
						// }
						// that.$refs.selectPopup.addGoods(that.$refs.selectPopup.goodsList[0])
						// //添加后清空
						// that.$refs.selectPopup.pageInfo.goods_no = ''
						// that.$refs.selectPopup.getGoodsById()
					},
					fail(err) {
						uni.$u.toast('扫描失败请重新扫码')
					}
				});
			},
			//时间选择器
			dateConfirm(e) {
				this.show = false
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
				console.log(this.fileList1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://api.wanwucloud.cn/api/upload/img', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							AuthorToken: this.$store.state.user.userInfo.token
						},
						success: (res) => {
							let successRes = JSON.parse(res.data)
							if (successRes.code == 200) {
								uni.hideLoading();

								setTimeout(() => {
									resolve(successRes.data.url);
									uni.$u.toast(successRes.msg)
								}, 500);

							} else {
								uni.hideLoading();
								uni.$u.toast(successRes.msg)
							}
						}
					});
				});
			},
			manualSelection() {
				this.showManualSelectionPopup = true;
			},
			//获取分类列表
			async getSectionList() {
				const {
					data: {
						data
					}
				} = await getSectionListApi()
				let parentList = data.map(item => {
					let obj = {
						id: item.id,
						label: item.label,
						parent_id: item.parent_id
					}
					return obj
				})
				this.columns.push(parentList)
				this.columnData = data.map(item => {
					return item.children
				})
				this.columns.push(this.columnData[0])
			},
			//选择器
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData[index])
				}
			},
			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				console.log('confirm', e)
				this.sectionPickerShow = false
			},
			//提交
			async submit() {
				await this.$refs.uForm.validate()
				if (this.cartList.length == 0) return uni.$u.toast('请选择要借用的物料')
				const newList = this.fileList1.map(item => {
					return item.url
				})
				const str = newList.join(',')
				const detaliList = this.cartList.map(item => {
					const obj = {
						goods_id: item.goods_id,
						goods_name: item.goods_name,
						quantity: item.quantity,
						price: item.price,
					}
					return obj
				})
				this.formData.apply_time = this.formData.apply_time + ''
				this.formData = {
					...this.formData,
					details: detaliList,
					attachment: str
				}
				await receiveAndBorrowApi(this.formData)

				setTimeout(() => {
					uni.$u.toast('借用申请提交成功')
				}, 500)
				this.formData = {
					apply_time: Number(new Date()),
					project: '',
					remark: '',
					ware_id: this.$store.state.user.stashInfo.ware_id,
					shipment_type: 23, // 1 领取 2 借用
					dept_id: 0, //部门
					attachment: '', //附件信息
				}
				this.fileList1 = []
				this.clearCart()
				this.change()
			},
			showProject() {
				this.showProjectPopup = true
			}
		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter);
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		background-color: #b3d7ff;
		min-height: 100vh;

		.top_box {
			height: 200rpx;

			.title {
				margin: 40rpx 0 20rpx 60rpx;
				font-size: 40rpx;
				font-weight: 600;
			}

			::v-deep .u-steps-item__wrapper--row {
				background-color: #b3d7ff;
			}
		}

		.information_entry {
			background-color: #fff;
			margin: 0 10rpx;
			padding: 30rpx 20rpx;
			border-radius: 20rpx;

			::v-deep .u-form-item__body__left {
				margin-left: 20rpx;
			}

			::v-deep .u-upload__wrap__preview {
				width: 110rpx;
				height: 110rpx;
			}

			::v-deep .u-upload__wrap__preview__image {
				width: 110rpx !important;
				height: 110rpx !important;
			}
		}

		.scan_code {
			display: flex;
			justify-content: space-between;
			background-color: #fff;
			border-radius: 20rpx;
			margin: 10rpx;
			padding: 40rpx;
			font-size: 30rpx;

			.left_box {
				display: flex;
				align-items: center;
				height: 90rpx;

				image {
					width: 90rpx;
					height: 90rpx;
					margin-right: 20rpx;
				}
			}

			.right_box {
				display: flex;
				align-items: center;
				border-left: 1px solid #32a3df;
				height: 90rpx;

				image {
					width: 70rpx;
					height: 70rpx;
					margin-right: 20rpx;
				}
			}
		}

		.cargo_list {
			background-color: #fff;
			border-radius: 20rpx;
			min-height: 500rpx;
			margin: 0 10rpx;
			padding: 20rpx;
			margin-bottom: 170rpx;

			.big_title {
				font-weight: 700;
				font-size: 35rpx;
			}

			.tips {
				margin-left: 40rpx;
				font-size: 25rpx;
				color: #f9b85c;
			}

			.empty_box {
				margin: 40rpx 0;
			}
		}

		.bottom_box {
			display: flex;
			justify-content: center;
			align-items: center;
			z-index: 99;
			position: fixed;
			bottom: 0;
			width: 100%;
			height: 160rpx;
			background-color: #f0f3f8;

			.submit_btn {
				width: 600rpx;
			}
		}
	}

	.upload_box {
		width: 110rpx;
		height: 110rpx;
		border: 1px dashed #ccc;
		text-align: center;
		line-height: 110rpx;
		font-size: 40rpx;
		color: #ccc;
	}
</style>